/* uart.c
* Copyright (C) 2006  Benedikt Sauter
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/

#include <inttypes.h>
#include <avr/io.h>
#include <avr/pgmspace.h>

#include "uart.h"

/**
 * Init function for USART0
 * 38400 8N1
 **/
void uart_init (void)
{
  UBRR0H = 0;
  UBRR0L = 25;
  UCSR0B = (1 << RXEN0) | (1 << TXEN0);
  UCSR0C = (0 << USBS0) | (3 << UCSZ00);
}

/**
 * Sends one char through USART0
 * \param char - the char to be send
 */
void uart_putchar (char data)
{
  /* Wait for empty transmit buffer */
  while (!(UCSR0A & (1 << UDRE0))) ;
  /* Put data into buffer, sends the data */
  UDR0 = data;
}

uint8_t uart_getchar (void)
{
  while (!(UCSR0A & (1 << RXC0))) ;	// warten bis Zeichen verfuegbar
  return UDR0;
}

void uart_write (const char *msg)
{
  while (*msg != '\0')
    uart_putchar (*msg++);
}

void uart_sendhex(uint8_t hex)
{
  uint8_t nibble;

  nibble = hex >> 4;
  if (nibble <= 9)
    uart_putchar (nibble + 48);
  else
    uart_putchar (nibble + 87);

  nibble  = hex & 0x0F;
  if (nibble <= 9)
    uart_putchar (nibble + 48);
  else
    uart_putchar (nibble + 87);
}
